﻿using FSM.IBll;
using FSM.Model;
using FSM.Web.Models;
using FSM.Web.Models.Fileter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FSM.Web.Controllers.PersonalCenter
{
    [Authorize]
    public class PersonalController : BaseController
    {
        #region 模块

        private DataResultModel drm;

        private readonly ISysUserBll _userBll;

        private readonly IWebHostEnvironment _hostingEnvironment;

        private readonly ILogLoginBll _logLoginbll;

        #endregion

        #region 构造函数

        public PersonalController(ISysUserBll userBll, ILogLoginBll logLoginbll, IWebHostEnvironment hostingEnvironment)
        {
            this._userBll = userBll;
            this._hostingEnvironment = hostingEnvironment;
            this._logLoginbll = logLoginbll;
            drm = new DataResultModel();
            ModuleNo = "0201";
        }

        #endregion

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ResultExceptionFilter]
        [OperateAuthorize("0201", "Query")]
        public JsonResult Get()
        {
            string userNo = AuthencationHelper.GetLoginUserNo(User);
            var userInfo = _userBll.Get(userNo);
            drm.success = true;
            drm.data = new { 
                userInfo.user_no,
                userInfo.user_name,
                userInfo.user_sex,
                userInfo.user_email,
                userInfo.user_mobile,
                userInfo.avatar
            };
            return drm.ToJson();
        }

        /// <summary>
        /// 更新个人信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        [ResultExceptionFilter]
        [ValidateAntiForgeryToken]
        [OperateAuthorize("0201", "Edit")]
        public JsonResult Update(sys_user user)
        {
            user.user_no = AuthencationHelper.GetLoginUserNo(User);
            user.creater = user.user_no;
            if( _userBll.Update(user)==false)
            {
                throw new Exception("更新个人信息失败");
            }
            drm.success = true;
            return drm.ToJson();
        }

        public IActionResult UpdatePassword()
        {
            return View();
        }

        /// <summary>
        /// 更新密码
        /// </summary>
        /// <param name="old_pwd">旧密码</param>
        /// <param name="new_pwd">新密码</param>
        /// <returns></returns>
        [HttpPost]
        [ResultExceptionFilter]
        [OperateAuthorize("0202", "Edit")]
        [ValidateAntiForgeryToken]
        public JsonResult UpdatePassword(string old_pwd, string new_pwd)
        {
            string userNo = AuthencationHelper.GetLoginUserNo(User);
            if (_userBll.UpdatePassword(userNo, old_pwd, new_pwd) == false)
            {
                throw new Exception("修改密码失败");
            }
            drm.success = true;
            return drm.ToJson();
        }

        [HttpPost]
        [ResultExceptionFilter]
        [OperateAuthorize("0202", "Edit")]
        public JsonResult UploadAvtar()
        {
            string userNo = AuthencationHelper.GetLoginUserNo(User);
            if (Request.Form.Files.Count > 0)
            {
                var file = Request.Form.Files[0];
                string avatar = $"{userNo}{System.IO.Path.GetExtension(file.FileName)}";
                string filePath = $"/wwwroot/resources/avatar/{avatar}";
                string fullPath = $"{_hostingEnvironment.ContentRootPath}{filePath}";
                using (System.IO.FileStream fs = new System.IO.FileStream(fullPath, System.IO.FileMode.Create))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                if (!_userBll.UpdateAvatar(userNo, userNo, avatar))
                {
                    throw new Exception("更新头像失败");
                }
                drm.success = true;
                drm.message = filePath;
            }
            else
            {
                drm.success = false;
                drm.message = "上传的图片不能为空且大小不能为0kb";
            }
            return drm.ToJson();
        }

        /// <summary> 
        /// 查询 
        /// </summary> 
        /// <param name="start_date">查询启始日期</param> 
        /// <param name="end_date">查询结束日期</param> 
        /// <param name="log_user">登录人員</param> 
        /// <param name="log_type">登录类型
        /// 1：網頁  
        /// 2：移動APP
        /// 3：Api</param> 
        /// <param name="log_terminal">登录设备
        /// 1：电脑
        /// 2：手机
        /// 3：Pad</param> 
        /// <param name="log_ip">登录IP</param> 
        [HttpPost]
        [ResultExceptionFilter]
        [OperateAuthorize("0201", "Query")]
        public JsonResult LoginLogs(int? log_type, int? log_terminal, string log_ip, int? page = 1, int? page_size = 30)
        {
            string userNo = AuthencationHelper.GetLoginUserNo(User);
            Tuple<List<log_login>, int> result = _logLoginbll.ListPagin(null, null, userNo, log_type, log_terminal, log_ip, page.Value, page_size.Value);
            drm.success = true;
            drm.data = result.Item1;
            drm.total = result.Item2;
            return new JsonResult(drm);
        }
    }
}
